package com.hexinfo.dmpro.component.data.transfer.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class ShellUtil {

    private static Logger logger = LoggerFactory.getLogger(ShellUtil.class);

    public final static String SHELL_RESULT = "SHELL_RESULT";
    public final static String SHELL_ERR_RESULT = "SHELL_ERR_RESULT";
    public final static String SHELL_INPUT_RESULT = "SHELL_INPUT_RESULT";
    public final static String SHELL_PID = "SHELL_PID";
    public final static String INVOKE_STATUS = "INVOKE_STATUS";

    public static Map exec(String shell) {
        logger.info("执行命令为：" + shell);
        String[] newShell = {shell};
        return exec(newShell, "UTF-8");
    }

    public static Map exec(String[] shell, String charset) {
        Map retMap = new HashMap();
        try {
            Process pid = null;
            pid = Runtime.getRuntime().exec(shell);
            retMap.put(SHELL_PID, pid.toString());
            logger.info("shell pid: " + pid.toString());

            if (pid != null) {
                StreamGobbler errorStream = new StreamGobbler(pid
                        .getErrorStream(), charset);
                errorStream.start();
                StreamGobbler inputStream = new StreamGobbler(pid
                        .getInputStream(), charset);
                inputStream.start();
                int exitCode = pid.waitFor();

                logger.info("返回码：" + exitCode);
                logger.info("错误流：" + errorStream.getContent());
                logger.info("正确流：" + inputStream.getContent());
                retMap.put(SHELL_RESULT, String.valueOf(exitCode));
                retMap.put(SHELL_ERR_RESULT, errorStream.getContent());
                retMap.put(SHELL_INPUT_RESULT, inputStream.getContent());

                if ("0".equals(String.valueOf(exitCode))) {
                    retMap.put(INVOKE_STATUS, true);
                } else {
                    retMap.put(INVOKE_STATUS, false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put(INVOKE_STATUS, false);
        }
        return retMap;
    }

    public static Map exec(String[] shell) {
        return exec(shell, "UTF-8");
    }

}
